<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="120px"
        >
            <el-form-item label="姓名" prop="realName">
                <el-input
                    v-model="queryParams.realName"
                    placeholder="请输入姓名"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="工号" prop="staffNum">
                <el-input
                    v-model="queryParams.staffNum"
                    placeholder="请输入工号"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="签订日期区间" prop="daterange">
                <el-date-picker
                    v-model="queryParams.timeArr"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                >
                </el-date-picker>
            </el-form-item>
            <!-- <el-form-item label="有效期时间" prop="daterange">
                <el-date-picker
                    v-model="timeArr"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    @change="setChangeDate($event, 'startdate', 'enddate')"
                >
                </el-date-picker>
            </el-form-item> -->

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >查询</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <TableCard>
            <el-row :gutter="10" class="mb8">
                <!-- <el-col :span="1.5">
                  <el-button
                      type="primary"
                      plain
                      icon="el-icon-plus"
                      size="mini"
                      @click="handleAdd"
                      v-hasPermi="['back:contract:add']"
                      >新签合同</el-button
                  >
              </el-col>
              <el-col :span="1.5">
                  <el-button
                      type="success"
                      plain
                      icon="el-icon-edit"
                      size="mini"
                      :disabled="single"
                      @click="handleUpdate"
                      v-hasPermi="['back:contract:edit']"
                      >修改</el-button
                  >
              </el-col>
              <el-col :span="1.5">
                  <el-button
                      type="danger"
                      plain
                      icon="el-icon-delete"
                      size="mini"
                      :disabled="multiple"
                      @click="handleDelete"
                      v-hasPermi="['back:contract:remove']"
                      >删除</el-button
                  >
              </el-col>
              <el-col :span="1.5">
                  <el-button
                      type="warning"
                      plain
                      icon="el-icon-download"
                      size="mini"
                      @click="handleExport"
                      v-hasPermi="['back:contract:export']"
                      >导出</el-button
                  >
              </el-col> -->
            </el-row>

            <el-table
                :border="Global.tableShowBorder"
                v-loading="loading"
                :data="contractList"
                @selection-change="handleSelectionChange"
            >
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <!-- <el-table-column label="合同id" align="center" prop="id" /> -->
                <el-table-column
                    type="index"
                    label="序号"
                    width="55"
                    align="center"
                />

                <el-table-column label="姓名" align="center" prop="realName" />
                <el-table-column label="工号" align="center" prop="staffNum" />

                <el-table-column
                    label="任职部门"
                    align="center"
                    prop="deptName"
                />
                <el-table-column
                    label="担任岗位"
                    align="center"
                    prop="postName"
                />

                <el-table-column
                    label="签订日期"
                    align="center"
                    prop="signdate"
                    width="180"
                >
                    <template slot-scope="scope">
                        <span>{{
                            parseTime(scope.row.signdate, "{y}-{m}-{d}")
                        }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="合同有效期"
                    align="center"
                    prop=""
                    width="200"
                >
                    <template slot-scope="scope">
                        <span>{{
                            parseTime(scope.row.startdate, "{y}-{m}-{d}") +
                            `至` +
                            `${
                                scope.row.enddate
                                    ? parseTime(
                                          scope.row.enddate,
                                          "{y}-{m}-{d}"
                                      )
                                    : "—"
                            }`
                        }}</span>
                    </template>
                </el-table-column>

                <el-table-column
                    label="经办人"
                    align="center"
                    prop="operatorName"
                />
                <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                    width="200"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handleView(scope.row)"
                            >查看</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                v-show="total > 10"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </TableCard>

        <!-- 添加劳动合同对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="1200px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="员工" prop="realName">
                                <el-input
                                    readonly
                                    @focus="showTableDialog"
                                    v-model="form.realName"
                                    placeholder="请选择员工"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="合同编号" prop="contractNum">
                                <el-input
                                    v-model="form.contractNum"
                                    placeholder="请输入合同编号"
                                />
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="12">
                            <el-form-item label="工号" prop="staffNum">
                                <el-input
                                    disabled
                                    v-model="form.staffNum"
                                    placeholder="请输入工号"
                                />
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="12">
                            <el-form-item label="任职部门" prop="deptId">
                                <treeselect
                                    v-model="form.deptId"
                                    :options="deptOptions"
                                    :show-count="true"
                                    placeholder="请选择部门"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="担任岗位" prop="postId">
                                <el-select
                                    filterable
                                    v-model="form.postId"
                                    placeholder="请选择岗位"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in postList"
                                        :key="item.postId"
                                        :label="item.postName"
                                        :value="item.postId"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="签订日期" prop="signdate">
                                <el-date-picker
                                    clearable
                                    v-model="form.signdate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择签订日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <!-- <el-form-item label="岗位" prop="postId">
                            <span>{{ parsePostName(form.postId) }}</span>
                        </el-form-item> -->

                        <!-- <el-form-item label="部门" prop="orgId">
                            <span>{{ parseSelectTree(form.deptId) }}</span>
                        </el-form-item> -->
                        <el-col :span="12">
                            <el-form-item label="试用期" prop="probationPeriod">
                                <el-select
                                    filterable
                                    v-model="form.probationPeriod"
                                    placeholder="请选择试用期"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in timeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item
                                label="有效期开始日期"
                                prop="startdate"
                            >
                                <el-date-picker
                                    clearable
                                    v-model="form.startdate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择有效期开始日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="有效期截止日期" prop="enddate">
                                <el-date-picker
                                    clearable
                                    v-model="form.enddate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择有效期截止日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="服务期履行记录" prop="record">
                                <el-input
                                    v-model="form.record"
                                    type="textarea"
                                    :rows="5"
                                    placeholder=""
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="备注" prop="remark">
                                <el-input
                                    v-model="form.remark"
                                    type="textarea"
                                    :rows="5"
                                    placeholder=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经办人" prop="operatorName">
                                <el-input
                                    readonly
                                    @focus="
                                        () => {
                                            showUserTableVision = true;
                                        }
                                    "
                                    v-model="form.operatorName"
                                    placeholder="请选择经办人"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">保 存</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加修改合同弹窗 -->
        <el-dialog
            :title="title"
            :visible.sync="changeOpen"
            width="1200px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="130px"
                >
                    <el-row>
                        <el-col :span="24">
                            <el-divider content-position="center"
                                >员工信息</el-divider
                            ></el-col
                        >
                        <el-col :span="12">
                            <el-form-item label="员工" prop="realName">
                                <el-input
                                    disabled
                                    readonly
                                    @focus="showTableDialog"
                                    v-model="form.realName"
                                    placeholder="请选择员工"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="员工编号" prop="staffNum">
                                <el-input
                                    disabled
                                    v-model="form.staffNum"
                                    placeholder="请输入员工编号"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="已签订合同的次数" prop="num">
                                <div>{{ form.num }}次</div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-divider content-position="center"
                                >合同信息</el-divider
                            ></el-col
                        >
                        <el-col :span="12">
                            <el-form-item label="合同编号" prop="contractNum">
                                <el-input
                                    v-model="form.contractNum"
                                    placeholder="请输入合同编号"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="合同状态" prop="status">
                                <dict-tag
                                    :options="dict.type.contract_status"
                                    :value="form.status"
                                ></dict-tag>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="签订日期" prop="signdate">
                                <el-date-picker
                                    clearable
                                    v-model="form.signdate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择签订日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <!-- <el-col :span="12">
                        <el-form-item label="工号" prop="staffNum">
                            <el-input
                                disabled
                                v-model="form.staffNum"
                                placeholder="请输入工号"
                            />
                        </el-form-item>
                    </el-col> -->
                        <el-col :span="12">
                            <el-form-item label="任职部门" prop="deptId">
                                <treeselect
                                    v-model="form.deptId"
                                    :options="deptOptions"
                                    :show-count="true"
                                    placeholder="请选择部门"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="担任岗位" prop="postId">
                                <el-select
                                    filterable
                                    v-model="form.postId"
                                    placeholder="请选择岗位"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in postList"
                                        :key="item.postId"
                                        :label="item.postName"
                                        :value="item.postId"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!-- nextIsDo 是否签订下一份合同 -->

                        <!-- <el-form-item label="岗位" prop="postId">
                        <span>{{ parsePostName(form.postId) }}</span>
                    </el-form-item> -->

                        <!-- <el-form-item label="部门" prop="orgId">
                        <span>{{ parseSelectTree(form.deptId) }}</span>
                    </el-form-item> -->
                        <el-col :span="12">
                            <el-form-item
                                v-if="form.num <= 1"
                                label="试用期/见习期"
                                prop="probationPeriod"
                            >
                                <el-select
                                    filterable
                                    v-model="form.probationPeriod"
                                    placeholder="请选择试用期"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in timeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                v-if="form.num > 1"
                                label="续签时长"
                                prop="isFixed"
                            >
                                <el-radio-group v-model="form.isFixed">
                                    <el-radio :label="1">固定期限合同</el-radio>
                                    <el-radio :label="0"
                                        >无固定期限合同</el-radio
                                    >
                                </el-radio-group>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item
                                label="有效期开始日期"
                                prop="startdate"
                            >
                                <el-date-picker
                                    clearable
                                    v-model="form.startdate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择有效期开始日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item
                                :disabled="form.isFixed == 0"
                                label="有效期截止日期"
                                prop="enddate"
                            >
                                <el-date-picker
                                    clearable
                                    v-model="form.enddate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择有效期截止日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="服务期履行记录" prop="record">
                                <el-input
                                    v-model="form.record"
                                    type="textarea"
                                    :rows="5"
                                    placeholder="请输入服务期履行记录"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="备注" prop="remark">
                                <el-input
                                    v-model="form.remark"
                                    type="textarea"
                                    :rows="5"
                                    placeholder="请输入备注"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经办人" prop="operatorName">
                                <el-input
                                    readonly
                                    @focus="
                                        () => {
                                            showUserTableVision = true;
                                        }
                                    "
                                    v-model="form.operatorName"
                                    placeholder="请选择经办人"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">保 存</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 查看合同弹窗 -->

        <el-dialog
            :title="title"
            :visible.sync="viewOpen"
            width="1200px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="130px"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="姓名">
                                <el-input
                                    disabled
                                    readonly
                                    @focus="showTableDialog"
                                    v-model="form.realName"
                                    placeholder="请选择姓名"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="工号">
                                <el-input
                                    disabled
                                    v-model="form.staffNum"
                                    placeholder="请输入工号"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="合同编号">
                                <el-input
                                    disabled
                                    v-model="form.contractNum"
                                    placeholder="请输入合同编号"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="任职部门">
                                <treeselect
                                    disabled
                                    v-model="form.deptId"
                                    :options="deptOptions"
                                    :show-count="true"
                                    placeholder="请选择部门"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="担任岗位">
                                <el-select
                                    disabled
                                    filterable
                                    v-model="form.postId"
                                    placeholder="请选择岗位"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in postList"
                                        :key="item.postId"
                                        :label="item.postName"
                                        :value="item.postId"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="签订日期">
                                <el-date-picker
                                    clearable
                                    disabled
                                    v-model="form.signdate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择签订日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item disabled label="有效期开始日期">
                                <el-date-picker
                                    clearable
                                    disabled
                                    v-model="form.startdate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择有效期开始日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="有效期截止日期">
                                <el-date-picker
                                    disabled
                                    v-if="form.isFixed"
                                    clearable
                                    v-model="form.enddate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择有效期截止日期"
                                >
                                </el-date-picker>
                                <span v-else>—</span>
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="服务期履行记录">
                                <el-input
                                    disabled
                                    v-model="form.record"
                                    type="textarea"
                                    :rows="5"
                                    placeholder="请输入服务期履行记录"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="备注">
                                <el-input
                                    disabled
                                    v-model="form.remark"
                                    type="textarea"
                                    :rows="5"
                                    placeholder="请输入备注"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经办人">
                                <el-input
                                    disabled
                                    readonly
                                    @focus="
                                        () => {
                                            showUserTableVision = true;
                                        }
                                    "
                                    v-model="form.operatorName"
                                    placeholder="请选择经办人"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                disabled
                                v-if="form.num <= 1"
                                label="试用期/见习期"
                            >
                                <el-select
                                    filterable
                                    disabled
                                    v-model="form.probationPeriod"
                                    placeholder="请选择试用期"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in timeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">关 闭</el-button>
            </div>
        </el-dialog>

        <table-dialog :open.sync="showTableVision" @confirm="setFormBase">
        </table-dialog>
        <userTableDialog
            title="经办人"
            :defaultParams="defaultParams"
            :open.sync="showUserTableVision"
            @confirm="setPeratorName"
        >
        </userTableDialog>
    </div>
</template>

<script>
import {
    listContract,
    getContract,
    delContract,
    addContract,
    updateContract,
    getContractUser,
} from "@/api/back/contract";
import tableDialog from "../tableDialog.vue";
import { treeselect } from "@/api/system/dept";
import { listPostAll } from "@/api/system/post";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { mapGetters } from "vuex";
import dayjs from "dayjs";
const today = dayjs().format("YYYY-MM-DD");

// 获取今天的 yyyy-MM-dd 格式的时间

export default {
    name: "Contract",
    dicts: ["contract_status", "contract_termination_reason"],
    data() {
        //合同编号规则
        var contractNumMaxLength = (rule, value, callback) => {
            if (value && value.length > 64) {
                callback(new Error("长度不能超过 64 个字符"));
            } else {
                callback();
            }
        };
        //服务器履行记录和备注规则
        var recordMaxLength = (rule, value, callback) => {
            if (value && value.length > 500) {
                callback(new Error("长度不能超过 64 个字符"));
            } else {
                callback();
            }
        };
        //签订日期规则
        var contractDate_1 = (rule, value, callback) => {
            if (this.form.isFixed == 0) {
                //无固定期限合同，跳过验证
                callback();
            }

            if (
                value != null &&
                this.form.enddate != null &&
                this.compareDates(value, this.form.enddate) == 1
            ) {
                callback(new Error("签订日期应在有效期截止日期之前"));
            } else {
                callback();
            }
        };
        //开始日期规则
        var contractDate_2 = (rule, value, callback) => {
            if (this.form.isFixed == 0) {
                //无固定期限合同，跳过验证
                callback();
            }
            if (
                value != null &&
                this.form.enddate != null &&
                this.compareDates(value, this.form.enddate) != -1
            ) {
                callback(new Error("有效期开始日期应在有效期截止日期之前"));
            } else {
                callback();
            }
        };
        return {
            timeList: [
                { value: 0, label: "0个月" },
                { value: 1, label: "1个月" },
                { value: 2, label: "2个月" },
                { value: 3, label: "3个月" },
                { value: 4, label: "4个月" },
                { value: 5, label: "5个月" },
                { value: 6, label: "6个月" },
                { value: 7, label: "7个月" },
                { value: 8, label: "8个月" },
                { value: 9, label: "9个月" },
                { value: 10, label: "10个月" },
                { value: 11, label: "11个月" },
                { value: 12, label: "12个月" },
            ],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 劳动合同表格数据
            contractList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                status: 3,
                timeArr:[],
        
                realName: null,
                staffNum: null,
                startdate: null,
                enddate: null,
                userId: null,
                signdate: null,
                orgId: null,
                orgName: null,
                postId: null,
                postName: null,
                probationPeriod: null,
                nextIsDo: null,
                record: null,
                operatorId: null,
                operatorName: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                realName: [
                    {
                        required: true,
                        message: "员工名字不能为空",
                        trigger: "change",
                    },
                ],
                staffNum: [
                    {
                        required: true,
                        message: "员工编号不能为空",
                        trigger: "blur",
                    },
                ],
                startdate: [
                    {
                        validator: contractDate_2,
                        message: "有效期开始日期应在有效期截止日期之前",
                        trigger: "blur",
                    },
                    {
                        required: true,
                        message: "有效期开始时间不能为空",
                        trigger: "blur",
                    },
                ],
                userId: [
                    {
                        required: true,
                        message: "员工id不能为空",
                        trigger: "blur",
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: "任职部门不能为空",
                        trigger: "change",
                    },
                ],
                signdate: [
                    {
                        validator: contractDate_1,
                        message: "签订日期应在有效期截止时间之前",
                        trigger: "blur",
                    },
                    {
                        required: true,
                        message: "签订日期不能为空",
                        trigger: "blur",
                    },
                ],
                postId: [
                    {
                        required: true,
                        message: "担任岗位不能为空",
                        trigger: "change",
                    },
                ],
                postName: [
                    {
                        required: true,
                        message: "岗位名称不能为空",
                        trigger: "blur",
                    },
                ],
                nextIsDo: [
                    {
                        required: true,
                        message: "0：未签下一份合同，1：已签下一份合同不能为空",
                        trigger: "blur",
                    },
                ],
                operatorId: [
                    {
                        required: true,
                        message: "经办人id不能为空",
                        trigger: "blur",
                    },
                ],
                operatorName: [
                    {
                        required: true,
                        message: "经办人名字不能为空",
                        trigger: "change",
                    },
                ],
                contractNum: [
                    {
                        validator: contractNumMaxLength,
                        message: "长度不能超过 64 个字符",
                        trigger: "blur",
                    },
                ],
                record: [
                    {
                        validator: recordMaxLength,
                        message: "长度不能超过 500 个字符",
                        trigger: "blur",
                    },
                ],
                remark: [
                    {
                        validator: recordMaxLength,
                        message: "长度不能超过 500 个字符",
                        trigger: "blur",
                    },
                ],
            },
            showTableVision: false,
            deptOptionsArray: [],
            postList: [],
            deptOptions: [],

            defaultParams: {
                isLink: true,
                //在职用户，
                staffType: "4",
            },
            showUserTableVision: false,

            //修改弹窗参数
            changeOpen: false,

            //查看弹窗参数
            viewOpen: false,
            //续约弹窗参数
            xqOpen: false,
            endOpen: false, //中止合同
        };
    },

    computed: {
        ...mapGetters(["userId", "realName", "staffNum"]),
    },
    components: { tableDialog, Treeselect },

    showUserTableVision: false,
    created() {
        this.getList();
        this.getTreeselect();
        this.getPostList();
    },
    methods: {
        initOperator() {
            if (this.staffNum) {
                this.form.operatorId = this.userId;
                this.form.operatorName = this.realName;
            }
        },
        setPeratorName(row) {
            this.form.operatorId = row.userId;
            this.form.operatorName = row.realName;
        },
        //比较两个时间先后
        compareDates(dateString1, dateString2) {
            // 尝试将字符串解析为Date对象
            const date1 = new Date(dateString1);
            const date2 = new Date(dateString2);

            // 检查是否解析成功（即不是Invalid Date）
            if (isNaN(date1.getTime()) || isNaN(date2.getTime())) {
                console.error("Invalid date string");
                return null; // 或者你可以抛出一个错误
            }

            // 比较日期
            if (date1 < date2) {
                return -1; // dateString1 在 dateString2 之前
            } else if (date1 > date2) {
                return 1; // dateString1 在 dateString2 之后
            } else {
                return 0; // 两个日期相同
            }
        },
        getPostList() {
            listPostAll().then((res) => {
                this.postList = res.data;
            });
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
                this.deptOptionsArray = this.flattenArray(this.deptOptions);
            });
        },
        flattenArray(arr) {
            let result = [];
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                result.push(item);
                if (item.children) {
                    result = result.concat(this.flattenArray(item.children));
                }
            }
            return result;
        },
        parseSelectTree(id) {
            console.log(this.deptOptionsArray, "this.deptOptionsArray");
            let tempObj = this.deptOptionsArray.find((item) => item.id == id);
            if (tempObj) {
                return tempObj.label;
            }
            return "—";
        },
        parsePostName(ids) {
            if (!ids) {
                return "—";
            }
            if (ids != null && ids != "") {
                let nameArr = [];
                let selIds = ids.split(",");
                this.postList.forEach((item) => {
                    selIds.forEach((sel) => {
                        if (item.postId == sel) {
                            nameArr.push(item.postName);
                        }
                    });
                });
                if (nameArr.length <= 0) {
                    return "—";
                }
                return nameArr.join(",");
            }
        },
        parsePostSigleName(ids) {
            if (!ids) {
                return "—";
            }
            if (ids != null && ids != "") {
                let nameArr = [];

                this.postList.forEach((item) => {
                    if (item.postId == ids) {
                        nameArr.push(item.postName);
                    }
                });
                if (nameArr.length <= 0) {
                    return "—";
                }
                return nameArr.join(",");
            }
        },

        showTableDialog() {
            this.showTableVision = true;
        },
        //设置带入信息
        setFormBase(row) {
            let temp = { ...row };
            console.log(temp, "temp");
            this.form.orgId = temp.orgId;
            this.form.orgName = this.parseSelectTree(temp.orgId);

            if (temp.postId) {
                let tempList = temp.postId.split(",");
                if (tempList.length > 0) {
                    this.form.postId = Number(tempList[0]);
                }
            }
            this.form.postName = this.parsePostSigleName(this.form.postId);
            this.form.staffNum = temp.staffNum;
            this.form.userId = temp.userId;
            this.form.deptId = temp.deptId;
            this.form.deptName = this.parseSelectTree(temp.deptId);
            this.form.operatorId = 1;
            console.log(this.form, "this.form");
            this.$set(this.form, "realName", temp.realName);
        },
        /** 查询劳动合同列表 */
        getList() {
            this.loading = true;
            const tempParams = this.queryParams;
            if (tempParams.timeArr && tempParams.timeArr.length > 0) {
                tempParams.signStartDate = tempParams.timeArr[0];
                tempParams.signEndDate = tempParams.timeArr[1];
            } else {
                tempParams.signStartDate = null;
                tempParams.signEndDate = null;
            }
            listContract(tempParams).then((response) => {
                this.contractList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            //bug 101

            if (this.$store.getters.allDefectObj["HR-WEB-100"] == 0) {
                this.resetQuery();
            }

            this.open = false;
            this.viewOpen = false;
            this.changeOpen = false;
            this.xqOpen = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                realName: null,
                staffNum: null,
                startdate: null,
                enddate: null,
                userId: null,
                signdate: null,
                orgId: null,
                orgName: null,
                postId: null,
                postName: null,
                probationPeriod: null,
                nextIsDo: null,
                record: null,
                remark: null,
                operatorId: null,
                operatorName: null,
                createTime: null,
                createBy: null,
                updateBy: null,
                updateTime: null,
            };
            this.resetForm("form");
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.queryParams.timeArr = [];
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.initOperator();
            this.title = "新签合同";
        },

        //获取合同签订次数
        getNums() {
            getContractUser({
                staffNum: this.form.staffNum,
            }).then((response) => {
                this.form.num = response.data.num;
            });
        },

        // 查看按钮操作
        handleView(row) {
            this.reset();
            const id = row.id || this.ids;

            getContract(id).then((response) => {
                this.form = response.data;
                this.getNums();
                if (!this.form.isFixed && this.form.isFixed != 0) {
                    this.form.isFixed = "1";
                }

                this.viewOpen = true;
                this.title = "查看合同";
            });
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
            // this.$router.push({
            //     path: "/hrm/contract/carrying/form/" + row.staffNum,
            //     query: { readonly: "1" },
            // });
            this.reset();
            const id = row.id || this.ids;

            getContract(id).then((response) => {
                this.form = response.data;
                this.getNums();
                if (!this.form.isFixed) {
                    this.form.isFixed = "1";
                }
                this.changeOpen = true;
                this.title = "修改合同";
            });
        },

        //终止弹窗
        handleEnd(row) {
            this.reset();
            const id = row.id || this.ids;

            getContract(id).then((response) => {
                this.form = response.data;
                this.getNums();
                if (!this.form.isFixed) {
                    this.form.isFixed = "1";
                }
                this.endOpen = true;
                this.title = "终止合同";
            });
        },

        //续签按钮操作
        handleXq(row) {
            this.reset();
            const id = row.id || this.ids;

            getContract(id).then((response) => {
                //续签调用
                this.form.id = null;

                this.form = response.data;
                //续签合同默认为空
                this.form.contractNum = "";
                //签订日期默认为今天
                console.log(this.form.signdate);
                console.log(today);
                this.form.signdate = today;
                this.form.isFixed = 1;
                //合同开始时间默认比之前+1天
                this.form.startdate1 = this.form.startdate;
                this.form.enddate1 = this.form.enddate;
                this.form.startdate = dayjs(this.form.startdate)
                    .add(1, "day")
                    .format("YYYY-MM-DD");
                this.form.enddate = "";

                this.getNums();
                if (!this.form.isFixed) {
                    this.form.isFixed = "固定期限合同";
                }
                this.xqOpen = true;
                this.title = "续签合同";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updateContract(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;

                            this.viewOpen = false;
                            this.changeOpen = false;
                            this.xqOpen = false;
                            this.getList();
                        });
                    } else {
                        this.$confirm(
                            "保存合同后，合同不可以删除，您确定要保存吗？",
                            "提示",
                            {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "warning",
                            }
                        )
                            .then(() => {
                                addContract(this.form).then((response) => {
                                    this.open = false;
                                    this.viewOpen = false;
                                    this.changeOpen = false;
                                    this.xqOpen = false;
                                    this.$message({
                                        type: "success",
                                        message: "新增成功",
                                    });

                                    this.getList();
                                });
                            })
                            .catch(() => {
                                this.$message({
                                    type: "info",
                                    message: "已取消新增",
                                });
                            });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm('是否确认删除劳动合同编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delContract(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "back/contract/export",
                {
                    ...this.queryParams,
                },
                `contract_${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>
